import { render, h } from 'vue'
import messageComponent from '../components/message/message.vue'

let container: HTMLDivElement
const containerClassName = 'kc-message-wrapper'
export const Message = (message: string, icon = '', duration = 2000, fn: () => void = () => {}) => {
  if (!document.querySelector('.' + containerClassName)) {
    container = document.createElement('div')
    container.className = containerClassName
    container && document.body.append(container)
  }
  const handleDestroy = () => {
    // 从 body 上移除组件

    render(null, container)

    container && document.body.removeChild(container)
    // Message关闭回调
    fn && fn()
  }

  // 使用 h 函数创建 vnode
  const vnode = h(messageComponent, {
    message,
    icon,
    duration,
    destroy: handleDestroy
  })
  // 使用 render 函数将 vnode 渲染为真实DOM并挂载到 body 上
  render(vnode, container)
}
